package com.example.lp.lpdesignpatterns.thread;

import java.util.concurrent.locks.ReentrantLock;

import java.util.concurrent.locks.ReentrantLock;

public class LockExample {
    private final ReentrantLock fairLock = new ReentrantLock(true); // true代表公平锁
    private final ReentrantLock unFairLock = new ReentrantLock(false); // false代表不公平锁

    public void fairLockTest() {
        for (int i = 0; i < 5; i++) {
            try {
                fairLock.lock();
                System.out.println(Thread.currentThread().getName() + " 获取了公平锁");
                Thread.sleep(500L);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                fairLock.unlock();
            }

        }
    }

    public void unFairLockTest() {
        for (int i = 0; i < 5; i++) {
            try {
                unFairLock.lock();
                System.out.println(Thread.currentThread().getName() + " 获取了不公平锁");
                Thread.sleep(500L);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                unFairLock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        LockExample lockExample = new LockExample();

//        Thread t1 = new Thread(() -> lockExample.fairLockTest(), "线程1");
//        Thread t2 = new Thread(() -> lockExample.fairLockTest(), "线程2");
//        t1.start();
//        t2.start();
////
        Thread t3 = new Thread(() -> lockExample.unFairLockTest(), "线程3");
        Thread t4 = new Thread(() -> lockExample.unFairLockTest(), "线程4");

        t3.start();
        t4.start();
    }
}

